<!--
 * @FilePath: activity-gl.vue
 * @@author: wjj
 * @Date: 2025-06-26 13:45:12
 * @@Description: new js file
-->
<template>
  <!-- <div style="display: flex"> -->
  <el-form
    :model="ActivityForm"
    :rules="rules"
    ref="ActivityForms"
    :inline="true"
  >
    <el-row>
      <el-form-item prop="url" size="small" label="url">
        <el-input
          v-model="ActivityForm.url"
          :min="1"
          style="width: 600px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-popover
          ref="popover"
          placement="bottom"
          :width="260"
          trigger="click"
        >
          <template #reference>
            <el-button
              ref="button"
              style="margin-right: 16px"
              :icon="Search"
              type="primary"
              plain
              @click="visible = visible ? false : true"
            >
              UserID
            </el-button>
          </template>
          <div ref="div_uid">
            <el-input v-model="user_phone" :min="1" style="width: 100%">
              <template #append>
                <el-button
                  :icon="Search"
                  style="background-color: #a7e0b1"
                  @click="sou_uid"
                />
              </template>
            </el-input>
            <el-row class="w-150px mb-2">
              <el-text truncated style="margin-right: 5px">nickname:</el-text>
              <el-text truncated style="color: green">{{ nickname }}</el-text>
            </el-row>
            <el-row class="w-150px mb-2">
              <el-text truncated style="margin-right: 5px">user_id:</el-text>
              <el-text truncated style="color: green">{{ user_id }}</el-text>
            </el-row>
            <el-row class="w-150px mb-2">
              <el-text truncated style="margin-right: 5px">虚拟🆔:</el-text>
              <el-text truncated style="color: green">
                {{ virtual_uid }}
              </el-text>
            </el-row>
          </div>
        </el-popover>
      </el-form-item>
      <el-form-item>
        <el-popover
          ref="popover"
          placement="bottom"
          :width="260"
          trigger="click"
        >
          <template #reference>
            <el-button
              ref="button"
              style="margin-right: 16px"
              :icon="Search"
              type="primary"
              plain
              @click="visible = visible ? false : true"
            >
              nimi-token
            </el-button>
          </template>
          <div>
            <el-input v-model="user_phone" :min="1" style="width: 100%">
              <template #append>
                <el-button
                  :icon="Search"
                  style="background-color: #a7e0b1"
                  @click="sou_token"
                />
              </template>
            </el-input>
            <el-input
              v-model="device_id"
              :min="1"
              style="width: 100%"
              clearable
            >
              <template #prepend>
                <span style="width: 30px">设备id</span>
              </template>
            </el-input>
            <el-row class="w-150px mb-2">
              <el-text truncated style="margin-right: 5px">token:</el-text>
              <el-text style="color: green">
                Bearer {{ nick_token }}
                <el-button
                  type="primary"
                  :icon="CopyDocument"
                  size="small"
                  @click="fallbackCopy('Bearer ' + nick_token)"
                />
              </el-text>
            </el-row>
          </div>
        </el-popover>
      </el-form-item>
      <el-form-item>
        <el-button
          ref="button"
          style="margin-right: 16px"
          type="primary"
          plain
          @click="saveUrl"
          v-has="`btn.Permission.add`"
        >
          保存url
        </el-button>
      </el-form-item>
    </el-row>
    <el-form-item prop="user_id" size="small" label="用户ID:">
      <el-input
        v-model="ActivityForm.user_id"
        :min="1"
        style="width: 100px"
      ></el-input>
    </el-form-item>
    <el-form-item prop="" size="small" label="时间范围:">
      <div>
        <el-date-picker
          v-model="time_values"
          type="datetimerange"
          start-placeholder="Start Date"
          end-placeholder="End Date"
          :default-time="defaultTime"
          @change="timeFunction"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="x"
        />
      </div>
    </el-form-item>
    <el-form-item prop="" size="small">
      <el-button
        class="login_btn"
        type="primary"
        plain
        size="default"
        @click="start"
      >
        搜索
      </el-button>
    </el-form-item>
    <el-form-item prop="" size="small">
      <el-popconfirm
        class="box-item"
        title="统计时间长，是查看历史记录还是统计？"
        placement="bottom"
        @confirm="tong"
      >
        <template #reference>
          <el-button
            class="login_btn"
            type="primary"
            plain
            size="default"
            :disabled="tong_status"
            v-has="`btn.Activity.start`"
          >
            统计
          </el-button>
        </template>
      </el-popconfirm>
    </el-form-item>
    <el-form-item prop="user_id" size="small" label="活动次数:">
      <el-input
        v-model="activity_count"
        :min="1"
        style="width: 100px"
      ></el-input>
    </el-form-item>
    <el-form-item prop="" size="small">
      <el-button
        class="login_btn"
        type="primary"
        plain
        size="default"
        @click="activity_dl = true"
        :disabled="tong_status"
      >
        历史记录与ROI
      </el-button>
    </el-form-item>
  </el-form>
  <el-card style="margin: 10px 0px; border-radius: 50px">
    <el-table :data="activity_Data" style="margin: 10px 0px" border>
      <el-table-column label="图片" align="center">
        <!-- 忽略 -->
        <!-- eslint-disable -->
        <template #="{ row, $index }">
          <el-image
            :src="'https://img.nimiproject.com/' + row.image_url"
            fit="scale-down"
            style="max-width: 100%"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="时间" align="center" />
      <el-table-column prop="user_id" label="用户🆔" align="center" />
      <el-table-column prop="name" label="礼物名" align="center" />
      <el-table-column prop="price" label="礼物价值" align="center" />
      <el-table-column prop="reward_id" label="礼物🆔" align="center" />
      <el-table-column prop="reward_nums" label="礼物数量" align="center" />
      <el-table-column prop="reward_days" label="礼物天数" align="center" />
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasRole"
      @size-change="sizeChange"
    />
  </el-card>

  <!-- </div> -->
  <el-dialog v-model="activity_dl" title="概率统计">
    总次数：
    <el-input v-model="activity_count" :min="1" style="width: 100px"></el-input>
    单价
    <el-input v-model="one_price" :min="1" style="width: 100px"></el-input>
    <el-button
      type="primary"
      plain
      size="default"
      @click="ROI"
      style="margin-left: 5px"
    >
      ROI
    </el-button>
    <span
      style="color: red; font-weight: bold; margin-left: 5px"
      v-if="ROI_status"
    >
      统计结果：{{ ROI_count }}/{{ activity_count * one_price }} =
      {{ ROI_count / (activity_count * one_price) }}
    </span>
    <el-table
      :data="tongTableData"
      style="width: 100%"
      @selection-change="selectChange"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column prop="name" label="礼物" width="280" />
      <el-table-column prop="price" label="价值" width="180" />
      <el-table-column prop="count" label="数量" width="180" />
      <el-table-column prop="gl" label="概率" width="180" />
    </el-table>
  </el-dialog>
</template>

<script lang='ts' setup >
defineOptions({
  name: 'activityGl', //与路由名一致，可使用缓存
  // inheritAttrs: false,
  // 其他自定义选项
})
import { ref, reactive, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
import useSocketClient from '@/store/socket/socket_client'
import emmit from '@/utils/emitter'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import axios from 'axios'
import { Search } from '@element-plus/icons-vue'
import { CopyDocument } from '@element-plus/icons-vue'
import { fallbackCopy, nimi_login, sleep } from '@/utils/common'
// 挂载完毕
//onMounted(()=>{})
//监控数据
//watch(select, (newVal, oldVal) => {})
//搜索uid
let visible = ref(false)
let nickname = ref('')
let nick_token = ref('')
let device_id = ref('185ae413009a8ac1')
let user_id = ref('')
let virtual_uid = ref('')
let one_price = ref(50)
let ROI_status = ref(false)
let ROI_count = ref(1)
let selectIdArr = ref<any[]>([])
const selectChange = (value: any) => {
  selectIdArr.value = value
  console.log(selectIdArr.value)
}
const ROI = () => {
  ROI_count.value = 0
  if (selectIdArr.value.length <= 0) {
    ElMessage.error('还没数据')
    return
  }
  if (one_price.value <= 0 || activity_count.value <= 0) {
    ElMessage.error('单价与总数不对')
    return
  }
  for (let index = 0; index < selectIdArr.value.length; index++) {
    const element = selectIdArr.value[index]
    // if (dao_key.length === 0 || dao_key.includes(element.gift)) {
    ROI_count.value = ROI_count.value + element.price * element.count
  }
  ROI_status.value = true
}
const getUrl = () => {
  request
    .get('/nimi/activity/restful-url')
    .then((res: any) => {
      console.log(res)
      ActivityForm.url = res.ac_url
      console.log(ActivityForm.url)
    })
    .then(() => {
      start()
    })
}
const saveUrl = () => {
  request
    .post('/nimi/activity/restful-url', {
      ac_url: ActivityForm.url,
    })
    .then((res: any) => {
      console.log(res)
      getUrl()
    })
}
const sou_token = async () => {
  if (user_phone.value == '') {
    ElMessage.error('请输入手机号')
    return
  }

  // 使用 axios 发起 post 请求(推荐)
  const res: any = await nimi_login(user_phone.value, device_id.value)
  console.log(res)
  if (!res) {
    ElMessage.error('请求异常')
    return
  }
  if (res.data.code == 0) {
    nick_token.value = res.data.data.jwt_token.access_token
    fallbackCopy('Bearer ' + nick_token.value)
  } else {
    nick_token.value = ''
    ElMessage.error(res.data.msg)
  }
}
const sou_uid = () => {
  if (user_phone.value == '') {
    ElMessage.error('请输入手机号')
    return
  }
  const params = new URLSearchParams(ActivityForm.url)
  const iam_session = params.get('iam_session') // 获取单个参数
  const admin_sid = params.get('admin_sid')
  const data_params = {
    iam_session: iam_session,
    admin_sid: admin_sid,
  }
  // 使用 axios 发起 GET 请求(推荐)
  axios
    .get(
      'http://test.nimiproject.com/api/ms/v1/nimi/admin/users?phone_num=%2B86+' +
        user_phone.value,
      {
        params: data_params, // 查询参数
      },
    )
    .then((response: any) => {
      console.log(response.data)
      if (response.data.result == 0) {
        user_id.value = response.data.data.basic_info.uid_str
        nickname.value = response.data.data.basic_info.nickname
        virtual_uid.value = response.data.data.virtual_user_info.virtual_uid
        fallbackCopy(user_id.value)
      } else {
        user_id.value = ''
        nickname.value = ''
        virtual_uid.value = ''
        ElMessage.error(response.data.message)
      }
    })
    .catch((error: any) => {
      console.error(error)
    })
}
let user_phone = ref('18818880000')
let activity_dl = ref(false)
let tong_status = ref(false)
let activity_count = ref(1000)
//当前页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(10)

//职位总个数
let total = ref<number>(0)
let ActivityForm = reactive({
  url: 'http://test.nimiproject.com/api/ms/v1/nimi/admin/activity/reward-records?page_num=1&page_size=10&iam_session=session.iam.5c9e1509c00244524daa&admin_sid=session.iam.5c9e1509c00244524daa',
  user_id: '',
  start_ts: '',
  end_ts: '',
})
const rules = {
  //规则对象属性:
  //required,代表这个字段务必要校验的
  //min:文本长度至少多少位
  //max:文本长度最多多少位
  //message:错误的提示信息
  //type: 'number'数字
  //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则

  url: [
    {
      required: true,
      message: '不能为空',
      trigger: 'change',
    },
  ],
}
const time_values = ref('')

const defaultTime: [Date, Date] = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 0, 0),
] // '12:00:00', '08:00:00'
const timeFunction = (value: any) => {
  if (!time_values.value) {
    console.log('清空')
    ActivityForm.start_ts = ''
    ActivityForm.end_ts = ''
  }
  if (time_values.value.length == 2) {
    ActivityForm.start_ts = String((time_values.value[0] as any) / 1000)
    ActivityForm.end_ts = String((time_values.value[1] as any) / 1000)
  }
  //   console.log(value[0])
}
let activity_Data = ref<any[]>([])
let tong_Data = ref<any[]>([])
let tong_total = ref(0)
let status = ref(false)
const axios_get = async (sou = true) => {
  //获取浏览器参数
  const params = new URLSearchParams(ActivityForm.url)
  const iam_session = params.get('iam_session') // 获取单个参数
  const admin_sid = params.get('admin_sid')
  const data_params = {
    page_num: pageNo.value,
    page_size: pageSize.value,
    iam_session: iam_session,
    admin_sid: admin_sid,
    user_id: ActivityForm.user_id,
    start_ts: ActivityForm.start_ts,
    end_ts: ActivityForm.end_ts,
  }

  // 过滤空值参数
  const filteredParams = Object.fromEntries(
    Object.entries(data_params).filter(
      ([_, value]) => value !== null && value !== undefined && value !== '',
    ),
  )
  axios
    .get(ActivityForm.url.split('?')[0], {
      params: filteredParams, // 查询参数
    })
    .then((response: any) => {
      if (response.data.result == 0) {
        if (sou) {
          activity_Data.value = response.data.data.records
          total.value = response.data.data.total_num
        } else {
          tong_Data.value = [...tong_Data.value, ...response.data.data.records]
          tong_total.value = response.data.data.total_num
          status.value = true
        }
      } else {
        ElMessage.error('无数据')
      }
    })
    .catch((error: any) => {
      console.error(error)
    })
}
const start = () => {
  console.log(ActivityForm.end_ts)
  console.log(ActivityForm.start_ts)
  // 使用 axios 发起 GET 请求(推荐)
  console.log(ActivityForm.url.split('?')[0])
  axios_get()
}
let tongTableData = ref<any[]>([])
const type_str = {
  '0': 'Gift',
  '1': 'Frame',
  '2': 'Bubble',
  '3': 'Card',
  '4': 'Title',
  '5': 'Ring',
  '7': 'Theme',
  '8': 'Gold',
  '9': 'Vehicle',
  '10': 'FamilyCoin',
  '11': 'Bits',
}
const tong = async () => {
  status.value = false
  tong_Data.value = []
  tongTableData.value = []
  tong_status.value = true
  if (ActivityForm.user_id && ActivityForm.start_ts && ActivityForm.end_ts) {
    // //获取浏览器参数
    // const params = new URLSearchParams(ActivityForm.url)
    // const iam_session = params.get('iam_session') // 获取单个参数
    // const admin_sid = params.get('admin_sid')
    // const python_params = {
    //   iam_session: iam_session,
    //   admin_sid: admin_sid,
    //   user_id: ActivityForm.user_id,
    //   start_ts: ActivityForm.start_ts,
    //   end_ts: ActivityForm.end_ts,
    //   url: ActivityForm.url.split('?')[0],
    // }

    // // 过滤空值参数
    // const filteredParams = Object.fromEntries(
    //   Object.entries(python_params).filter(
    //     ([_, value]) => value !== null && value !== undefined && value !== '',
    //   ),
    // )
    // // 使用 axios 发起 GET 请求(推荐)
    // request
    //   .get('/nimi/activity/activity_gl', {
    //     params: filteredParams, // 查询参数
    //   })
    //   .then((response: any) => {
    //     console.log(response.data)
    //   })
    //   .catch((error: any) => {
    //     console.error(error)
    //   })

    ////////////////////////////////////////////////////////////////////
    let temp = pageSize.value
    let temp1 = pageNo.value
    pageSize.value = 100
    pageNo.value = 1
    axios_get(false)
    for (let index = 0; index < 10; index++) {
      if (status.value) {
        break
      }
      await sleep(1)
    }
    let for_num =
      Math.floor(tong_total.value / 100) -
      (tong_total.value % 100 === 0 ? 1 : 0)
    for (let index = 0; index < for_num; index++) {
      status.value = false
      pageNo.value = pageNo.value + 1
      axios_get(false)
      for (let index = 0; index < 10; index++) {
        if (status.value) {
          break
        }
        await sleep(1)
      }
    }
    const key_map = new Map()
    for (let index = 0; index < tong_Data.value.length; index++) {
      const element = tong_Data.value[index]
      if (!key_map.has(element.reward_id + String(element.reward_nums))) {
        key_map.set(element.reward_id + String(element.reward_nums), {
          name: '', // 预分配空间
          price: 0,
          count: 0,
          gl: 0,
        })
      }
      const temp_map = key_map.get(
        element.reward_id + String(element.reward_nums),
      )
      temp_map.name =
        '【' +
        element.name +
        ' 】x ' +
        String(element.reward_nums ? element.reward_nums : element.reward_days)
      temp_map.price = element.price
      temp_map.count = temp_map.count + 1
      temp_map.gl = temp_map.count / activity_count.value
    }
    key_map.forEach((value, key) => {
      tongTableData.value.push(value)
      console.log(`Key: ${key}, Value: ${value}`)
    })
    console.log(tong_Data.value.length)
    console.log(tong_Data.value)
    pageSize.value = temp
    pageNo.value = temp1
    activity_dl.value = true
  } else {
    ElMessage.error('用户ID与时间必填')
  }
  tong_status.value = false
}
const getHasRole = async (pager = 1) => {
  //修改当前页码
  pageNo.value = pager
  axios_get()
}
//下拉菜单的回调
const sizeChange = () => {
  getHasRole()
}
// function sleep(time: number) {
//   return new Promise((resolve) => setTimeout(resolve, time * 1000))
// }
onMounted(() => {
  getUrl()
})
</script>
<style scoped lang='scss'>
</style>